package com.amumu.drama.common.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 幂等工具类
 */
@Component
public class IdempotentUtil {

    /**
     * 幂等key最长过期时间，30秒
     */
    private final int IDEMPOTENT_MAX_EXPIRE_TIME = 30_000 * 100;
    /**
     * 打标
     */
    private final String IDEMPOTENT_CONTROL_TAG = "idempotent_";

    @Autowired
    private LockHelper lockHelper;

    public boolean isIdempotent(String idempotentKey, int expireTime) {
        String key = String.format("%s_%s", IDEMPOTENT_CONTROL_TAG, idempotentKey);
        expireTime = Math.min(IDEMPOTENT_MAX_EXPIRE_TIME, expireTime);
        return !lockHelper.tryIncrement(key, IDEMPOTENT_CONTROL_TAG + System.currentTimeMillis(), expireTime);
    }

    public boolean isIdempotent(String idempotentKey) {
        return isIdempotent(idempotentKey, IDEMPOTENT_MAX_EXPIRE_TIME);
    }
}
